package com.gang.ssm.bos.system.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gang.ssm.bos.common.ShiroUser;
import com.gang.ssm.bos.core.anotation.Before;
import com.gang.ssm.bos.core.constant.SessionAttr;
import com.gang.ssm.bos.core.toolbox.ajax.AjaxResult;
import com.gang.ssm.bos.core.toolbox.captcha.Captcha;
import com.gang.ssm.bos.core.toolbox.kit.MenuUtils;
import com.gang.ssm.bos.system.bean.Menu;
import com.gang.ssm.bos.system.bean.User;
import com.gang.ssm.bos.system.meta.intercept.LoginValidator;
import com.gang.ssm.bos.system.meta.intercept.RequestValidator;
import com.gang.ssm.bos.system.service.MenuService;
import com.gang.ssm.bos.system.service.UserService;

@RequestMapping("/login")
@Controller
public class LoginController extends BosController{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MenuService menuService;
	
	@Before(RequestValidator.class)
	@RequestMapping("/loginUI")
	public String loginUI(HttpServletRequest request, 
			HttpServletResponse response) {
		return "login/login";
	}
	
	@Before(LoginValidator.class)
	@ResponseBody
	@RequestMapping("/checkUser")
	public AjaxResult checkUser(User user, String imgCode, HttpServletRequest request, 
			HttpServletResponse response) {
		
		if (!Captcha.validate(request, response, imgCode)) {
			return error("验证码错误");
		}
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = 
				new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
			ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
			//保存登录shiroUser到session
			request.getSession().setAttribute(SessionAttr.USER_LOGIN.getValue(), shiroUser);
			
			List<Integer> userMenuIds = userService.findMenuIdsByUserId(shiroUser.getId());
			List<Menu> menuList = menuService.getByParentId(0);
			//保存用户的所拥有菜单
			request.getSession().setAttribute(SessionAttr.USER_MENUS.getValue(), MenuUtils.getMenu(menuList, userMenuIds));
			
			return success("登录成功!");
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			return fail("账号或密码错误!");
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			return fail("账号或密码错误!");
		}
	}
	
	@RequestMapping("/captcha")
	public void captcha(HttpServletResponse response) {
		Captcha.init(response).render();
	}
}
